/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.railway.reports;

import com.railway.reports.utils.QueryBuilder;
import com.railway.utils.CustomScrollBarUI;
import com.railway.utils.RestServer;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 *
 * @author Kenny
 */
public class SalesCustomizer extends javax.swing.JPanel {

    private DefaultComboBoxModel dcbmStaff;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    private boolean range = false;
    private boolean type = false;
    private boolean staff = false;
    private boolean exception = false;
    private int initialHave = 0;
    private QueryBuilder qb;

    /**
     * Creates new form SalesCustomizer
     */
    public SalesCustomizer() {
        initComponents();
        populateStaff();
        jbgException.add(jrbMostHigh);
        jbgException.add(jrbMostLow);
    }

    private void populateStaff() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                dcbmStaff = new DefaultComboBoxModel();
                String result = RestServer.httpGet("staffDetail", "");
                try {
                    JSONObject json = new JSONObject(result);
                    boolean error = json.optBoolean("error");
                    if (!error) {
                        int statuscode = json.getInt("status");
                        if (statuscode == 200) {
                            JSONArray jsonArr = json.getJSONArray("content");
                            for (int i = 0; i < jsonArr.length(); i++) {
                                dcbmStaff.addElement(jsonArr.getJSONObject(i).getString("uid"));
                            }
                            jcbxStaff.setModel(dcbmStaff);
                        }
                    }
                } catch (JSONException ex) {
                    System.out.println(ex);
                }
            }
        }).start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jbgDateRange = new javax.swing.ButtonGroup();
        jbgException = new javax.swing.ButtonGroup();
        jlblSalesCustomizer = new javax.swing.JLabel();
        jsprCustomizer = new javax.swing.JSeparator();
        jycYear = new com.toedter.calendar.JYearChooser();
        jdcFrom = new com.toedter.calendar.JDateChooser();
        jlblAnd = new javax.swing.JLabel();
        jdcTo = new com.toedter.calendar.JDateChooser();
        jrbRangeYear = new javax.swing.JRadioButton();
        jrbRangeMonth = new javax.swing.JRadioButton();
        jrbRangeBetween = new javax.swing.JRadioButton();
        jspiMonth = new javax.swing.JSpinner();
        jcbRangeOfDate = new javax.swing.JCheckBox();
        jcbSalesType = new javax.swing.JCheckBox();
        jspStatus = new javax.swing.JScrollPane();
        jltSalesType = new javax.swing.JList();
        jcbStaff = new javax.swing.JCheckBox();
        jcbxStaff = new javax.swing.JComboBox();
        jcbException = new javax.swing.JCheckBox();
        jrbMostHigh = new javax.swing.JRadioButton();
        jlblPopItem = new javax.swing.JLabel();
        jspiMostPop = new javax.swing.JSpinner();
        jlblPopTop = new javax.swing.JLabel();
        jlblUnpopTop = new javax.swing.JLabel();
        jrbMostLow = new javax.swing.JRadioButton();
        jspiMostUnpop = new javax.swing.JSpinner();
        jlblUnpopItem = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(220, 220, 220), 2));
        setPreferredSize(new java.awt.Dimension(210, 340));
        setLayout(null);

        jlblSalesCustomizer.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jlblSalesCustomizer.setText("CRITERIA CUSTOMIZER");
        add(jlblSalesCustomizer);
        jlblSalesCustomizer.setBounds(10, 5, 200, 20);
        add(jsprCustomizer);
        jsprCustomizer.setBounds(5, 25, 200, 5);

        jycYear.setEnabled(false);
        add(jycYear);
        jycYear.setBounds(100, 50, 100, 20);

        jdcFrom.setEnabled(false);
        jdcFrom.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        add(jdcFrom);
        jdcFrom.setBounds(100, 90, 100, 20);

        jlblAnd.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jlblAnd.setText("and");
        jlblAnd.setEnabled(false);
        add(jlblAnd);
        jlblAnd.setBounds(40, 110, 60, 20);

        jdcTo.setEnabled(false);
        jdcTo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        add(jdcTo);
        jdcTo.setBounds(100, 110, 100, 20);

        jrbRangeYear.setBackground(new java.awt.Color(255, 255, 255));
        jbgDateRange.add(jrbRangeYear);
        jrbRangeYear.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jrbRangeYear.setSelected(true);
        jrbRangeYear.setText("Year");
        jrbRangeYear.setActionCommand("year");
        jrbRangeYear.setEnabled(false);
        jrbRangeYear.setFocusPainted(false);
        jrbRangeYear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbRangeYearActionPerformed(evt);
            }
        });
        add(jrbRangeYear);
        jrbRangeYear.setBounds(20, 50, 80, 20);

        jrbRangeMonth.setBackground(new java.awt.Color(255, 255, 255));
        jbgDateRange.add(jrbRangeMonth);
        jrbRangeMonth.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jrbRangeMonth.setText("Month");
        jrbRangeMonth.setActionCommand("month");
        jrbRangeMonth.setEnabled(false);
        jrbRangeMonth.setFocusPainted(false);
        jrbRangeMonth.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbRangeMonthActionPerformed(evt);
            }
        });
        add(jrbRangeMonth);
        jrbRangeMonth.setBounds(20, 70, 80, 20);

        jrbRangeBetween.setBackground(new java.awt.Color(255, 255, 255));
        jbgDateRange.add(jrbRangeBetween);
        jrbRangeBetween.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jrbRangeBetween.setText("Between");
        jrbRangeBetween.setActionCommand("between");
        jrbRangeBetween.setEnabled(false);
        jrbRangeBetween.setFocusPainted(false);
        jrbRangeBetween.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbRangeBetweenActionPerformed(evt);
            }
        });
        add(jrbRangeBetween);
        jrbRangeBetween.setBounds(20, 90, 80, 20);

        jspiMonth.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jspiMonth.setModel(new javax.swing.SpinnerNumberModel(1, 1, 12, 1));
        jspiMonth.setEnabled(false);
        add(jspiMonth);
        jspiMonth.setBounds(100, 70, 100, 20);

        jcbRangeOfDate.setBackground(new java.awt.Color(255, 255, 255));
        jcbRangeOfDate.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jcbRangeOfDate.setText("Range of Date");
        jcbRangeOfDate.setActionCommand("datePurchased");
        jcbRangeOfDate.setFocusPainted(false);
        jcbRangeOfDate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbRangeOfDateActionPerformed(evt);
            }
        });
        add(jcbRangeOfDate);
        jcbRangeOfDate.setBounds(10, 30, 190, 20);

        jcbSalesType.setBackground(new java.awt.Color(255, 255, 255));
        jcbSalesType.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jcbSalesType.setText("Sales Type");
        jcbSalesType.setFocusPainted(false);
        jcbSalesType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbSalesTypeActionPerformed(evt);
            }
        });
        add(jcbSalesType);
        jcbSalesType.setBounds(10, 130, 190, 20);

        jltSalesType.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jltSalesType.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "online", "walk-in" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jltSalesType.setEnabled(false);
        jspStatus.setViewportView(jltSalesType);

        jspStatus.getVerticalScrollBar().setUI(new CustomScrollBarUI());

        add(jspStatus);
        jspStatus.setBounds(30, 155, 170, 40);

        jcbStaff.setBackground(new java.awt.Color(255, 255, 255));
        jcbStaff.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jcbStaff.setText("Staff");
        jcbStaff.setFocusPainted(false);
        jcbStaff.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbStaffActionPerformed(evt);
            }
        });
        add(jcbStaff);
        jcbStaff.setBounds(10, 200, 180, 20);

        jcbxStaff.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jcbxStaff.setEnabled(false);
        add(jcbxStaff);
        jcbxStaff.setBounds(30, 220, 160, 20);

        jcbException.setText("Exception");
        jcbException.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jcbExceptionActionPerformed(evt);
            }
        });
        add(jcbException);
        jcbException.setBounds(10, 240, 160, 23);

        jrbMostHigh.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jrbMostHigh.setText("Most highest sales");
        jrbMostHigh.setActionCommand("mpi");
        jrbMostHigh.setEnabled(false);
        jrbMostHigh.setOpaque(false);
        jrbMostHigh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbMostHighActionPerformed(evt);
            }
        });
        add(jrbMostHigh);
        jrbMostHigh.setBounds(20, 260, 160, 23);

        jlblPopItem.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jlblPopItem.setText("Sales");
        jlblPopItem.setEnabled(false);
        add(jlblPopItem);
        jlblPopItem.setBounds(120, 280, 50, 20);

        jspiMostPop.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jspiMostPop.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
        jspiMostPop.setToolTipText("Zero to diisplay all");
        jspiMostPop.setEnabled(false);
        add(jspiMostPop);
        jspiMostPop.setBounds(70, 280, 40, 22);

        jlblPopTop.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jlblPopTop.setText("Top");
        jlblPopTop.setEnabled(false);
        add(jlblPopTop);
        jlblPopTop.setBounds(40, 280, 30, 20);

        jlblUnpopTop.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jlblUnpopTop.setText("Top");
        jlblUnpopTop.setEnabled(false);
        add(jlblUnpopTop);
        jlblUnpopTop.setBounds(40, 320, 30, 20);

        jrbMostLow.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jrbMostLow.setText("Most lowest sales");
        jrbMostLow.setActionCommand("mui");
        jrbMostLow.setEnabled(false);
        jrbMostLow.setOpaque(false);
        jrbMostLow.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jrbMostLowActionPerformed(evt);
            }
        });
        add(jrbMostLow);
        jrbMostLow.setBounds(20, 300, 170, 23);

        jspiMostUnpop.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jspiMostUnpop.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(0), Integer.valueOf(0), null, Integer.valueOf(1)));
        jspiMostUnpop.setToolTipText("Zero to diisplay all");
        jspiMostUnpop.setEnabled(false);
        add(jspiMostUnpop);
        jspiMostUnpop.setBounds(70, 320, 40, 20);

        jlblUnpopItem.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jlblUnpopItem.setText("Sales");
        jlblUnpopItem.setEnabled(false);
        add(jlblUnpopItem);
        jlblUnpopItem.setBounds(120, 320, 50, 20);
    }// </editor-fold>//GEN-END:initComponents

    private void jrbRangeYearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbRangeYearActionPerformed
        jycYear.setEnabled(true);
        jspiMonth.setEnabled(false);
        jdcFrom.setEnabled(false);
        jdcTo.setEnabled(false);
    }//GEN-LAST:event_jrbRangeYearActionPerformed

    private void jrbRangeMonthActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbRangeMonthActionPerformed
        jycYear.setEnabled(false);
        jspiMonth.setEnabled(true);
        jdcFrom.setEnabled(false);
        jdcTo.setEnabled(false);
    }//GEN-LAST:event_jrbRangeMonthActionPerformed

    private void jrbRangeBetweenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbRangeBetweenActionPerformed
        jycYear.setEnabled(false);
        jspiMonth.setEnabled(false);
        jdcFrom.setEnabled(true);
        jdcTo.setEnabled(true);
    }//GEN-LAST:event_jrbRangeBetweenActionPerformed

    private void jcbRangeOfDateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbRangeOfDateActionPerformed
        initialHave = 0;
        if (jcbRangeOfDate.isSelected()) {
            range = true;
            jrbRangeYear.setEnabled(true);
            jrbRangeMonth.setEnabled(true);
            jrbRangeBetween.setEnabled(true);
            jlblAnd.setEnabled(true);
            jycYear.setEnabled(true);
        } else {
            range = false;
            jrbRangeYear.setEnabled(false);
            jrbRangeMonth.setEnabled(false);
            jrbRangeBetween.setEnabled(false);
            jlblAnd.setEnabled(false);
            jycYear.setEnabled(false);
            jspiMonth.setEnabled(false);
            jdcFrom.setEnabled(false);
            jdcTo.setEnabled(false);
        }
    }//GEN-LAST:event_jcbRangeOfDateActionPerformed

    private void jcbStaffActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbStaffActionPerformed
        initialHave = 0;
        if (jcbStaff.isSelected()) {
            staff = true;
            jcbxStaff.setEnabled(true);
            jcbxStaff.setSelectedIndex(0);
        } else {
            staff = false;
            jcbxStaff.setEnabled(false);
            jcbxStaff.setSelectedIndex(0);
        }
    }//GEN-LAST:event_jcbStaffActionPerformed

    private void jcbSalesTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbSalesTypeActionPerformed
        initialHave = 0;
        if (jcbSalesType.isSelected()) {
            type = true;
            jltSalesType.setEnabled(true);
            jltSalesType.setSelectedIndex(0);
        } else {
            type = false;
            jltSalesType.setEnabled(false);
        }
    }//GEN-LAST:event_jcbSalesTypeActionPerformed

    private void jrbMostHighActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbMostHighActionPerformed
        jspiMostPop.setEnabled(true);
        jlblPopTop.setEnabled(true);
        jlblPopItem.setEnabled(true);
        jspiMostUnpop.setEnabled(false);
        jlblUnpopTop.setEnabled(false);
        jlblUnpopItem.setEnabled(false);
    }//GEN-LAST:event_jrbMostHighActionPerformed

    private void jrbMostLowActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jrbMostLowActionPerformed
        jspiMostPop.setEnabled(false);
        jlblPopTop.setEnabled(false);
        jlblPopItem.setEnabled(false);
        jspiMostUnpop.setEnabled(true);
        jlblUnpopTop.setEnabled(true);
        jlblUnpopItem.setEnabled(true);
    }//GEN-LAST:event_jrbMostLowActionPerformed

    private void jcbExceptionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jcbExceptionActionPerformed
        initialHave = 0;
        if (jcbException.isSelected()) {
            exception = true;
            jrbMostHigh.setEnabled(true);
            jrbMostHigh.setSelected(true);
            jrbMostLow.setEnabled(true);

            jspiMostPop.setEnabled(true);
            jlblPopTop.setEnabled(true);
            jlblPopItem.setEnabled(true);
        } else {
            exception = false;
            jrbMostHigh.setEnabled(false);
            jrbMostLow.setEnabled(false);

            jspiMostPop.setEnabled(false);
            jlblPopTop.setEnabled(false);
            jlblPopItem.setEnabled(false);

            jspiMostUnpop.setEnabled(false);
            jlblUnpopTop.setEnabled(false);
            jlblUnpopItem.setEnabled(false);
        }
    }//GEN-LAST:event_jcbExceptionActionPerformed

    private void rangeHaving() {
        String selectedRange = jbgDateRange.getSelection().getActionCommand();
        switch (selectedRange) {
            case "year":
                qb.having("YEAR(salesDate)", "" + jycYear.getValue());
                break;
            case "month":
                qb.having("MONTH(salesDate)", "" + jspiMonth.getValue());
                break;
            case "between":
                qb.havingBetween("salesDate", format.format(jdcFrom.getDate()), format.format(jdcTo.getDate()));
                break;
        }
    }

    private void rangeAnd() {
        String selectedRange = jbgDateRange.getSelection().getActionCommand();
        switch (selectedRange) {
            case "year":
                qb.and("YEAR(salesDate)", "" + jycYear.getValue());
                break;
            case "month":
                qb.and("MONTH(salesDate)", "" + jspiMonth.getValue());
                break;
            case "between":
                qb.andBetween("salesDate", format.format(jdcFrom.getDate()), format.format(jdcTo.getDate()));
                break;
        }
    }

    private void typeHaving() {
        List<String> typeList = jltSalesType.getSelectedValuesList();
        qb.having("transactionType", typeList.get(0));
        for (int i = 1; i < typeList.size(); i++) {
            qb.or("transactionType", typeList.get(i));
        }
    }

    private void typeAnd() {
        List<String> statusList = jltSalesType.getSelectedValuesList();
        if (!statusList.isEmpty()) {
            qb.and("transactionType", statusList.get(0));
            for (int i = 1; i < statusList.size(); i++) {
                qb.or("transactionType", statusList.get(i));
            }
        }
    }

//    private void staffAnd() {
//        if (jcbStaff.isSelected()) {
//            qb.and("madeBy", jcbxStaff);
//        }
//    }
    private void staffHaving() {
        qb.having("madeBy", jcbxStaff.getSelectedItem().toString());
    }

    private void staffAnd() {
        qb.and("madeBy", jcbxStaff.getSelectedItem().toString());
    }

    private void orderBySalesAmount() {
        if (jcbException.isSelected()) {
            exception = true;
            if (jrbMostHigh.isSelected()) {
                qb.orderBy("salesAmount", QueryBuilder.DESC, true);
                if ((int) jspiMostPop.getValue() != 0) {
                    qb.limit(Integer.parseInt(jspiMostPop.getValue().toString()));
                    System.out.println("DESC");
                }
            } else {
                qb.orderBy("salesAmount", QueryBuilder.ASC, true);
                if ((int) jspiMostUnpop.getValue() != 0) {
                    qb.limit(Integer.parseInt(jspiMostUnpop.getValue().toString()));
                    System.out.println("ASC");
                }
            }
        } else {
            exception = false;
        }
    }

    public String buildQuery() {
        qb = new QueryBuilder();
        qb.select("slogid", "salesAmount", "salesDate", "madeBy", "transactionType").from("saleslog");
        if (range) {
            System.out.println(initialHave);
            if (initialHave != 2 && initialHave != 3 && initialHave != 4) {
                initialHave = 1;
                rangeHaving();
            } else {
                rangeAnd();
            }
        }
        if (type) {
            System.out.println(initialHave);
            if (initialHave != 1 && initialHave != 3 && initialHave != 4) {
                initialHave = 2;
                typeHaving();
            } else {
                typeAnd();
            }
        }
        if (staff) {
            System.out.println(initialHave);
            if (initialHave != 1 && initialHave != 2 && initialHave != 4) {
                initialHave = 3;
                staffHaving();
            } else {
                staffAnd();
            }
        }
        if (exception) {
            System.out.println(initialHave);
            
//            if (initialHave != 1 && initialHave != 2 && initialHave != 3) {
                if(jcbException.isSelected()){
                initialHave = 4;
                orderBySalesAmount();
                }
//            }
        }
        System.err.println(qb.build());
        return qb.build();
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup jbgDateRange;
    private javax.swing.ButtonGroup jbgException;
    private javax.swing.JCheckBox jcbException;
    private javax.swing.JCheckBox jcbRangeOfDate;
    private javax.swing.JCheckBox jcbSalesType;
    private javax.swing.JCheckBox jcbStaff;
    private javax.swing.JComboBox jcbxStaff;
    private com.toedter.calendar.JDateChooser jdcFrom;
    private com.toedter.calendar.JDateChooser jdcTo;
    private javax.swing.JLabel jlblAnd;
    private javax.swing.JLabel jlblPopItem;
    private javax.swing.JLabel jlblPopTop;
    private javax.swing.JLabel jlblSalesCustomizer;
    private javax.swing.JLabel jlblUnpopItem;
    private javax.swing.JLabel jlblUnpopTop;
    private javax.swing.JList jltSalesType;
    private javax.swing.JRadioButton jrbMostHigh;
    private javax.swing.JRadioButton jrbMostLow;
    private javax.swing.JRadioButton jrbRangeBetween;
    private javax.swing.JRadioButton jrbRangeMonth;
    private javax.swing.JRadioButton jrbRangeYear;
    private javax.swing.JScrollPane jspStatus;
    private javax.swing.JSpinner jspiMonth;
    private javax.swing.JSpinner jspiMostPop;
    private javax.swing.JSpinner jspiMostUnpop;
    private javax.swing.JSeparator jsprCustomizer;
    private com.toedter.calendar.JYearChooser jycYear;
    // End of variables declaration//GEN-END:variables
}
